package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.QueryObject;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;


@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void insert(Region region) {
        region.setId(null);
        /*AssertUtil.hasLength(region.getName(),"区域名称不能为空");
        AssertUtil.hasLength(region.getSn(),"编号不能为空");
        if (StringUtils.isEmpty(region.getSequence())) {
            throw new LogicException("序号不能为空");
        }
        AssertUtil.hasLength(region.getInfo(),"简介不能为空");*/
        repository.save(region);
    }

    @Override
    public void update(Region region) {
        // 查询到原来的数据，如果输入的内容为空，使用设置的是原来的数据。
        //Region regionOld = repository.findById(region.getId()).orElse(null);
        repository.save(region);
    }

    @Override
    public void delete(String id) {

        repository.deleteById(id);

    }

    @Override
    public Region get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Region> listAll() {
        return repository.findAll();
    }

    @Override
    public Page<Region> query(QueryObject qo) {
        Query query = new Query();
        // 获取到 count
        long count = template.count(query,Region.class);
        if (count == 0){
            return Page.empty();
        }
        // 获取当前的数据 分页后的数据
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.ASC, "_id");
        query.with(pageable);
        // 分页查询
        List<Region> list = template.find(query, Region.class);
        return new PageImpl<>(list,pageable,count);
    }

    @Override
    public void changeHotValue(int hot, String id) {
        // 通过id查询到对象
        Region region = repository.findById(id).orElse(null);
        // 设置
        region.setIshot(hot);
        // 更新
        repository.save(region);
    }

    @Override
    public List<Region> hotRegion() {

        return repository.findByIshotOrderBySequence(Region.STATE_HOT);
    }


}
